<?php
namespace app\api\controller;
/**
 * 支付宝支付回调类
 * The file is part of the payment lib.
 * (c) Leo <dayugog@gmail.com>
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */
use think\facade\Db;

/**
 * Class TestNotify
 * @author  : helei
 * @date    : 2020/2/1 3:56 下午
 * @version : 1.0.0
 * @desc    : 测试异步通知
 *
 */
class RechargeNotify implements \Payment\Contracts\IPayNotify
{
 
    /**
     * @param string $channel 通知的渠道，如：支付宝、微信、招商
     * @param string $notifyType 通知的类型，如：支付、退款
     * @param string $notifyWay 通知的方式，如：异步 async，同步 sync
     * @param array $notifyData 通知的数据
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle(
        string $channel,
        string $notifyType,
        string $notifyWay,
        array $notifyData
    ) {
        if (isset($notifyData['result_code']) && $notifyData['result_code'] == 'SUCCESS'){
            $id = $notifyData['out_trade_no'];
            $this->todo($id,1);
        }elseif (isset($notifyData['trade_status']) && $notifyData['trade_status'] == 'TRADE_SUCCESS'){
            $id = $notifyData['out_trade_no'];
            $this->todo($id,2);
        }else{
            return false;
        }
    }

    public function todo($id,$type)
    {
        $order = Db::name('recharge')->where('id', $id)->find();
        if ($order['status'] == 1){
            return true;
        }
        Db::startTrans();
        try {
            // 修改支付状态
            Db::name('recharge')->where('id', $order['id'])->update(['status' => 1,'type' => $type]);
            $moneyLog = [
                'user_id' => $order['user_id'],
                'money' => $order['money'],
                'type' => 2,
                'status' => 1,
                'create_time' => toDate(time())
            ];
            Db::name('user')->where('user_id', $order['user_id'])->inc('money', $order['money'])->update();
            Db::name('money_log')->insert($moneyLog);
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            self::fileinput($e->getMessage());
            Db::rollback();
            return false;
        }
    }

    public function fileinput($str='测试数据:')
    {
        $date = date('Y-m-d H:i:s');
        $content = "alipay执行日期notify：".$date."\n".$str."\n\n";
        file_put_contents('AppPay.log', $content);
    }

}
